package com.dongdongshop.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

//    FilterFactoryBean 配置过滤器链
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // k:表示路径  v:表示放过还是拦截
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/login","anon"); // anon 表示不需要登录直接放过
        map.put("/css/**","anon"); // anon 表示不需要登录直接放过
        map.put("/img/**","anon"); // anon 表示不需要登录直接放过
        map.put("/js/**","anon"); // anon 表示不需要登录直接放过
        map.put("/plugins/**","anon"); // anon 表示不需要登录直接放过
        map.put("/**/**","authc"); // authc 表示必须登录才能访问

        //配置过滤器链所需要的资源
        filterFactoryBean.setFilterChainDefinitionMap(map);

        // 当请求拦截的话,让他跳转到登录页面
        filterFactoryBean.setLoginUrl("/toLogin");

        //当权限不足时跳转提示页面
        /*filterFactoryBean.setUnauthorizedUrl("/unauthorized");*/

        return filterFactoryBean;
    }
//    Subject： 用户主体（把操作交给SecurityManager）
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(loginRealm);
        return webSecurityManager;
    }
//    SecurityManager：安全管理器（关联Realm）
    //验证
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }
    //解密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5"); // 用什么加密,就用什么解密
        matcher.setHashIterations(3); //撒盐的次数 加密几次,解密就几次
        matcher.setStoredCredentialsHexEncoded(true); //设置编码
        return matcher;
    }

    // 配置ShiroDialect ,用于 thymeleaf 和 shiro 标签配合使用
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
